package com.game.config.dao.typeHandler;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@MappedJdbcTypes(JdbcType.VARCHAR) // 数据库类型
@MappedTypes({List.class}) // java数据类型
public class ListDouble2Handler extends BaseTypeHandler<List<Double>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Double> parameter, JdbcType jdbcType) throws SQLException {
        String serialized = JSONUtil.toJsonStr(parameter.stream().map(item -> item * 100.0).collect(Collectors.toList()));
        ps.setString(i, serialized);
    }

    @Override
    public List<Double> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String serialized = rs.getString(columnName);
        return JSONUtil.toList(serialized, Double.class).stream().map(item -> item / 100.0).collect(Collectors.toList());
    }

    @Override
    public List<Double> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String serialized = rs.getString(columnIndex);
        return JSONUtil.toList(serialized, Double.class).stream().map(item -> item / 100.0).collect(Collectors.toList());
    }

    @Override
    public List<Double> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String serialized = cs.getString(columnIndex);
        return JSONUtil.toList(serialized, Double.class).stream().map(item -> item / 100.0).collect(Collectors.toList());
    }

}
